package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 缓存商品类型--注意时间，前端设置了较短的超时时间，而调试时后端响应时间变长，导致前端未能接收到数据
     * @return
     */
    public Result queryTypeList()  {
        //Thread.sleep(500);//加上sleep就要在controller层、接口加上throws InterruptedException
        //用String类型redis存储
        String key = RedisConstants.CACHE_SHOP_TYPE_KEY;
        //查看redis数据
        String typeList = stringRedisTemplate.opsForValue().get(key);
        if(typeList != null){
            List<ShopType> shopTypeList = JSONUtil.toList(typeList, ShopType.class);
            return Result.ok(shopTypeList);
        }
        //redis不存在数据,查询数据库
        List<ShopType> shopTypeList = lambdaQuery().orderByAsc(ShopType::getSort).list();// 按 sort 升序排序
        if(shopTypeList == null){
            return Result.fail("商品类型发生错误");
        }
        //将查询到的数据缓存到redis
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shopTypeList));
        stringRedisTemplate.expire(key,RedisConstants.CACHE_SHOP_TYPE_TTL, TimeUnit.MINUTES);

        return Result.ok(shopTypeList);

    }
}
